/* api */
import { getCustomerTagList, setCustomerTagList } from '@src/api/SettingApi'
/* components */
import SettingPublicView from '@src/modules/setting/components/settingPublicView/index.vue'
import draggable from 'vuedraggable'
import BaseTags from '@src/component/common/BaseTags/index.ts'
/* entity */
import CustomerTag from '@model/entity/CustomerTag'
/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum'
import { BaseTagsTypeEnum } from '@src/component/common/BaseTags/BaseTags.tsx'
/* model */
import { SAVE_SUCCESS, VALUE_EMPTY } from '@src/model/const/Alert'
/* scss */
import '@src/modules/setting/customerTag/CustomerTagSetting.scss'
/* util */
import { isEmpty } from '@src/util/type'
import * as _ from 'lodash'
import Platform from '@src/util/platform'
/* vue */
import { Component } from 'vue-property-decorator'
import { CreateElement } from 'vue'
import VC from '@model/VC'
import i18n from '@src/locales'

enum CustomerTagSettingModeEnum {
  // 编辑模式
  Edit = 'edit',
  // 查看模式
  View = 'view'
}

const DragOptions = {
  animation: 380, 
  ghostClass: 'ghost'
}

const TagMaxNumber = 20

@Component({ 
  name: ComponentNameEnum.CustomerTagSetting,
  components: {
    draggable,
    [SettingPublicView.name]: SettingPublicView
  }
})
export default class CustomerTagSetting extends VC {
  
  // 客户标签列表
  private customerTags: CustomerTag[] = []
  // 客户标签列表编辑用的
  private customerTagsWithEdit: CustomerTag[] = []
  // 模式
  private mode: CustomerTagSettingModeEnum = CustomerTagSettingModeEnum.View
  // 等待状态
  private pending: boolean = false
  // 是否显示编辑标签弹窗
  private showTagEditDialog: boolean = false
  
  // 查看模式
  get isViewMode(): boolean {
    return this.mode === CustomerTagSettingModeEnum.View
  }
  
  // 编辑模式
  get isEditMode(): boolean {
    return this.mode === CustomerTagSettingModeEnum.Edit
  }
  
  get isTagMoreMax() {
    return this.customerTagsWithEdit.length == TagMaxNumber
  }
  
  private add() {
    this.customerTagsWithEdit.push(new CustomerTag())
  }
  
  private cancel() {
    this.hideTagEditModal()
  }
  
  private clearCustomerTagWithEditActive() {
    this.customerTagsWithEdit.forEach(customerTag => {
      customerTag.active = false
    })
  }
  
  private deleteTag(index: number): void {
    this.customerTagsWithEdit.splice(index, 1)
  }
  
  /**
   * @description 编辑客户标签
   * @return {void}
   */
  private edit(): void {
    this.customerTagsWithEdit = _.cloneDeep(this.customerTags)
    this.clearCustomerTagWithEditActive()
    this.openTagEditModal()
  }
  
  /**
   * @description 获取客户标签列表
   * @return {void}
   */
  private fetchCustomerTagList(): void {
    this.pending = true
    
    getCustomerTagList().then(data => {
      if (!data?.success) {
        return Platform.alert(data?.message)
      }
      
      this.pending = false
      // @ts-ignore
      this.customerTags = data?.data || []
    })
  }
  
  private fetchSetCustomerTagList() {
    this.pending = true
    
    const tags = this.customerTagsWithEdit.map((customerTag, index) => {
      return {
        ...customerTag,
        sort: index + 1
      }
    })
    
    setCustomerTagList({ tags }).then(data => {
      const isSuccess = Boolean(data?.success)
      
      Platform.notification({
        type: isSuccess ? 'success' : 'error',
        title: isSuccess ? i18n.t('common.base.saveSuccess') : i18n.t('common.base.saveFail'),
        message: isSuccess ? SAVE_SUCCESS : data?.message
      })
      
      if (!isSuccess) return
      
      this.customerTags = _.cloneDeep(tags)
      this.hideTagEditModal()
      this.fetchCustomerTagList()
    }).finally(() => {
      this.pending = false
    })
  }
  
  /**
   * @description 获取属性
  */
  private getAttributes() {
    return {
      class: 'customer-tag-setting-modal',
      props: {
        width: '775px',
        title: i18n.t('customer.tagSetting.title'),
        show: this.showTagEditDialog
      },
      on: {
        'update:show': (val: boolean) => {
          this.showTagEditDialog = val
        }
      },
      directives: [
        {
          name: 'loading',
          value: this.pending
        }
      ]
    }
  }
  
  private hideTagEditModal() {
    this.showTagEditDialog = false
  }
  
  private onInputFocusEventHandler(event: Event) {

  }
  
  private openTagEditModal() {
    this.showTagEditDialog = true
  }
  
  private save() {
    const validated = this.customerTagsWithEdit.every((customerTag: CustomerTag) => Boolean(customerTag.tagName))
    if (!validated) {
      return Platform.alert(VALUE_EMPTY)
    }
    
    this.fetchSetCustomerTagList()
  }
  
  private setViewMode() {
    this.mode = CustomerTagSettingModeEnum.View
  }
  
  private setEditMode() {
    this.mode = CustomerTagSettingModeEnum.Edit
  }
  
  private renderAddTagButton() {
    return (
      <el-button class='customer-tag-setting-add-button' type='ghost' onClick={() => this.add()}>
        <i class="iconfont icon-add2"></i>
        {i18n.t('customer.tagSetting.addTag')}
      </el-button>
    )
  }
  
  private renderTitleButton() {
    if (this.isViewMode) {
      return (
        <el-button disabled={this.pending} type='primary' onClick={() => this.edit()}>{i18n.t('common.base.edit')}</el-button>
      )
    }
    
    return (
      <div>
        <el-button onClick={() => this.cancel()}>{i18n.t('common.base.cancel')}</el-button>
        <el-button type='primary' onClick={() => this.save()}>{i18n.t('common.base.save')}</el-button>
      </div>
    )
  }
  
  private renderTitle() {
    return (
      <div class='customer-tag-setting-title'>
        <span class='customer-tag-setting-title-text'>{i18n.t('customer.tagSetting.title')}</span>
        { this.renderTitleButton() }
      </div>
    )
  }
  
  private renderContent() {    
    return this.renderContentWithViewMode()
  }
  
  private renderContentWithViewMode() {
    const isCustomerTagsEmpty = isEmpty(this.customerTags)
    
    return (
      <div class='customer-tag-setting-tags'>
        {
          isCustomerTagsEmpty ? (
            <div class='customer-tag-empty' onClick={() => this.edit()}>{i18n.t('customer.tagSetting.addTagTip')}</div>
          ) : (
            <BaseTags type={BaseTagsTypeEnum.Text} value={this.customerTags} />
          )
        }
      </div>
    )
  }
  
  private renderContentWithEditMode() {
    return (
      <div>
        <draggable
          class='customer-setting-tag-group'
          tag='div'
          {...DragOptions}
          value={this.customerTagsWithEdit}
          onInput={(value: CustomerTag[]) => this.customerTagsWithEdit = value}
        >
          { this.renderEditTagList() }
          { !this.isTagMoreMax && this.renderAddTagButton() }
        </draggable>
      </div>
    )
  }
  
  private renderEditTagList() {
    return (
      this.customerTagsWithEdit.map((customerTag: CustomerTag, index: number) => {
        return this.renderEditTagListItem(customerTag, index)
      })
    )
  }
  
  private renderEditTagListItem(customerTag: CustomerTag, index: number) {
    return (
      <div class='customer-setting-tag-item'>
        <i class="iconfont icon-tuozhuaipaixu drag-icon"></i>
        <el-input
          placeholder={i18n.t('common.placeholder.inputTagContent')}
          clearable 
          maxlength="10"
          value={customerTag.tagName} 
          onFocus={(event: Event) => this.onInputFocusEventHandler(event)}
          onInput={(value: string) => this.$set(this.customerTagsWithEdit[index], 'tagName', value.trim())}
        >
        </el-input>
        <i class="iconfont icon-delete delete-icon" onClick={() => this.deleteTag(index) }></i>
      </div>
    )
  }
  
  private renderTagEditModal() {
    const attrs = this.getAttributes()
    
    return (
      <base-modal {...attrs}>
        { this.renderContentWithEditMode() }
        <div slot="footer" class="dialog-footer">
          <el-button disabled={this.pending} type="ghost" onClick={() => this.cancel()}>
            {i18n.t('common.base.cancel')}
          </el-button>
          <el-button disabled={this.pending} type="primary" onClick={() => this.save()}>
            {i18n.t('common.base.save')}
          </el-button>
        </div>
      </base-modal>
    )
  }
  
  async mounted() {
    this.fetchCustomerTagList()
  }
  
  render(h: CreateElement) {
    return (
      <div class='customer-tag-setting'>
        <div class='customer-tag-box'>
          { this.renderTitle() }
          { this.renderContent() }
          { this.renderTagEditModal() }
        </div>
      </div>
    )
  }
}

